package com.yan.club.sys.control;

import com.yan.club.result.Result;
import com.yan.club.sys.model.SysCommunity;
import com.yan.club.sys.service.SysCommunityService;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static com.yan.club.auth.utils.SecurityUtil.getUser;
import static com.yan.club.result.ResultCode.INTERNAL_SERVER_ERROR;

/**
 * @author 彦
 * @since 2024/2/6 22:15
 */
@RestController
@RequestMapping("/sys/community")
public class SysCommunityController {

    @Resource
    private SysCommunityService sysCommunityService;

    /**
     * 获取社团列表
     */
    @PreAuthorize("@check.hasAuthority('system:dept:list')")
    @GetMapping("/list")
    public Result<List<SysCommunity>> list(SysCommunity dept) {
        List<SysCommunity> depts = sysCommunityService.selectDeptList(dept);
        return Result.success(depts);
    }

    /**
     * 新增社团
     */
    @PreAuthorize("@check.hasAuthority('system:dept:add')")
    @PostMapping
    public Result<String> add(@Validated @RequestBody SysCommunity dept) {
        if (sysCommunityService.checkDeptNameUnique(dept)) {
            return Result.error(INTERNAL_SERVER_ERROR.code,
                    "新增社团'" + dept.getDeptName() + "'失败，社团名称已存在");
        }

        return sysCommunityService.insertDept(dept);
    }

    /**
     * 修改社团
     */
    @PreAuthorize("@check.hasAuthority('system:dept:edit')")
    @PutMapping
    public Result<String> edit(@Validated @RequestBody SysCommunity dept) {
        Long deptId = dept.getDeptId();
        sysCommunityService.checkDeptDataScope(deptId);

        if (sysCommunityService.checkDeptNameUnique(dept)) {
            return Result.error(INTERNAL_SERVER_ERROR.code,
                    "修改社团'" + dept.getDeptName() + "'失败，社团名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return Result.error(INTERNAL_SERVER_ERROR.code,
                    "修改社团'" + dept.getDeptName() + "'失败，上级社团不能是自己");
        } else if ("1".equals(dept.getStatus()) && sysCommunityService.selectNormalChildrenDeptById(deptId) > 0) {
            return Result.error(INTERNAL_SERVER_ERROR.code,
                    "该社团种类包含未停用的社团！");
        }
        dept.setUpdateBy(getUser().getUserName());
        return (sysCommunityService.updateDept(dept));
    }

    /**
     * 根据社团编号获取详细信息
     */
    @PreAuthorize("@check.hasAuthority('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public Result<SysCommunity> getInfo(@PathVariable Long deptId) {
        sysCommunityService.checkDeptDataScope(deptId);
        return Result.success(sysCommunityService.selectDeptById(deptId));
    }

    /**
     * 删除社团
     */
    @PreAuthorize("@check.hasAuthority('system:dept:remove')")
    @DeleteMapping("/{deptId}")
    public Result<String> remove(@PathVariable Long deptId) {
        if (sysCommunityService.hasChildByDeptId(deptId)) {
            return Result.error(INTERNAL_SERVER_ERROR.code, "该社团种类种类存在社团,不允许删除");
        }
        if (sysCommunityService.checkDeptExistUser(deptId)) {
            return Result.error(INTERNAL_SERVER_ERROR.code, "社团存在社员,不允许删除");
        }
        sysCommunityService.checkDeptDataScope(deptId);
        return (sysCommunityService.deleteDeptById(deptId));
    }

    /**
     * 查询社团列表（排除节点）
     */
    @PreAuthorize("@check.hasAuthority('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public Result<List<SysCommunity>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysCommunity> depts = sysCommunityService.selectDeptList(new SysCommunity());

        // 排除自己 和 自己的父级
        depts.removeIf(d -> d.getDeptId().equals(deptId) ||
                ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return Result.success(depts);
    }

    /**
     * 得到所有社团种类
     */
    @PreAuthorize("@check.hasAuthority('system:dept:list')")
    @GetMapping("/listCategory")
    public Result<List<SysCommunity>> listCategory(SysCommunity dept) {
        List<SysCommunity> depts = sysCommunityService.listCategory(dept);
        return Result.success(depts);
    }

    /**
     * 得到所有社团
     */
    @PreAuthorize("@check.hasAuthority('system:dept:list')")
    @GetMapping("/listCommunity")
    public Result<List<SysCommunity>> listCommunity(SysCommunity dept) {
        List<SysCommunity> depts = sysCommunityService.listCommunity(dept);
        return Result.success(depts);
    }
}
